﻿using AutoMapper;
using B.S.BasicData.Api.Write.Applications.Command;
using B.S.BasicData.Domains;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructures;
using MediatR;

namespace B.S.BasicData.Api.Write.Applications.CommandHandler
{
    public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RolePermissons> rolepermissonsRepository;
        private readonly IBaseRepository<Role> roleRepository;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateRoleCommand> logger;

        public UpdateRoleCommandHandler(IBaseRepository<RolePermissons> rolepermissonsRepository, IBaseRepository<Role> roleRepository, IMapper mapper, ILogger<UpdateRoleCommand> logger)
        {
            this.rolepermissonsRepository = rolepermissonsRepository;
            this.roleRepository = roleRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "修改角色权限成功";
            using (var tran=roleRepository.DB.Database.BeginTransaction())
            {
                try
                {
                    logger.LogInformation("修改角色权限成功");
                    //角色
                    var role = mapper.Map<Role>(request);
                    role.CreateTime = DateTime.Now;
                    role.State = false;
                    await roleRepository.Update(role);
                    //角色权限
                    var listSelect = rolepermissonsRepository.GetAll().Where(x => x.RoleId == request.RoleId).ToList();
                    await rolepermissonsRepository.Delete(listSelect);
                    var list = new List<RolePermissons>();
                    foreach(var item in request.PermissonIds)
                    {
                        list.Add(new RolePermissons()
                        { 
                            RoleId = request.RoleId,
                            PermissonId = item
                        });
                    }
                    await rolepermissonsRepository.AddRange(list);
                    tran.Commit();
                }
                catch(Exception ex)
                {
                    logger.LogInformation("修改角色权限失败"+ex.Message);
                    result.Code = ApiEnum.Fail;
                    result.Message = "修改角色权限失败";
                    tran.Rollback();
                }
            }
            return await Task.FromResult(result);
        }
    }
}
